<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>通过wfs删除数据</title>
  <link rel="stylesheet" href="../js/lib/ol4.6.4/ol.css" type="text/css">
</head>
<body>
<div id="map"></div>
</body>
<script src="../js/lib/ol4.6.4/ol.js"></script>
<script src="../js/lib/jquery/jquery-3.3.1.min.js"></script>
<script>
  // 服务配置，命名空间、图层、服务地址等
  var geoserverData = {
    wsName: 'test',
    uri: 'http://www.openplans.org/test',
    wfsURL: 'http://localhost:8085/geoserver/wfs?',
    layer: 'port'
  }

  //测试数据 添加WFS数据  添加所有
  var wfsSource = new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    url: function (extent) {
      return (
              geoserverData.wfsURL + 'service=WFS&version=1.1.0&request=GetFeature&typeName=' +
              geoserverData.wsName + ":" +
              geoserverData.layer + '&' + 'outputFormat=application/json&srsname=EPSG:4326&bbox=' +
              extent.join(',') + ',EPSG:4326');
    },
    strategy: ol.loadingstrategy.bbox
  });

  let wfsLayer = new ol.layer.Vector({
    title: 'add Layer',
    source: wfsSource
  })

  var layers = [
    new ol.layer.Tile({
      source: new ol.source.XYZ({
                    url: "https://tile-a.openstreetmap.fr/hot/{z}/{x}/{y}.png"
                })
    }),wfsLayer
  ];

  var map = new ol.Map({
    target: 'map',
    layers: layers,
    view: new ol.View({
      projection: "EPSG:4326",
      center: [114, 31],
      zoom: 4
    })
  });

  let select = new ol.interaction.Select({
    layers:[wfsLayer],
    style: new ol.style.Style({
      image: new ol.style.Circle({
        radius: 8,
        fill: new ol.style.Fill({
          color: "#f00"
        })
      })
    })
  });

  select.on("select", function (e) {
    var features = e.selected;
    if(features.length>0){
      var feature = features[0];
      deleteFeature(feature);
      wfsLayer.getSource().changed();
    }
  });

  map.addInteraction(select);

  map.on('pointermove', function(evt) {
    if(map.hasFeatureAtPixel(evt.pixel)){
      $(map.getTargetElement()).css("cursor", "pointer");
    }else{
      $(map.getTargetElement()).css("cursor", "default");
    }
  });

  function deleteFeature(feature) {
    // 1、构造Feature
    ft = feature.clone()
    ft.setId(feature.getId());
    // 2、更新到后台
    let WFSTSerializer = new ol.format.WFS()
    var featObject = WFSTSerializer.writeTransaction(null,
            null, [ft], {
              featureNS: geoserverData.uri,
              featurePrefix: geoserverData.wsName,//工作空间名称
              featureType: geoserverData.layer,//图层名称
              srsName: 'EPSG:4326'
            });
    var serializer = new XMLSerializer()
    var featString = serializer.serializeToString(featObject)
    $.ajax({
      url: geoserverData.wfsURL,
      type:"POST",
      data: featString,
      contentType: 'text/xml',
      success: function (req) {
        console.log(req)
        alert("删除成功！")
        window.location.reload();
      },
      error: function (e) {
        alert("删除失败！"+e)
      }
    })
  }

</script>
</html>
